package com.ask.controller.user;

import com.ask.constant.StatusConstant;
import com.ask.entity.Dish;
import com.ask.result.Result;
import com.ask.service.DishService;
import com.ask.vo.DishVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController("userDishController")
@RequestMapping("/user/dish")
public class DishController {
    private static final Logger log = LoggerFactory.getLogger(DishController.class);
    @Autowired
    private DishService dishService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据分类条件查询菜品及口味
     *
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "dishCache", key = "#categoryId")
    public Result<List<DishVO>> listByCategoryId(Long categoryId) {

        // 1. 先查询redis,如果存在，直接返回
//        String key = RedisConstant.CACHE_DISH_KEY + categoryId;
//        List<DishVO> list = (List<DishVO>)redisTemplate.opsFo?rValue().get(key);

//        if (list != null && list.size() > 0) {
//            return Result.success(list);
//        }

        log.info("query dish,categoryId :{}", categoryId);
        // 2. 不存在，查询数据库
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        List<DishVO> dishVOList = dishService.listWithFlavor(dish);
        // 3. 查询结果存储至redis
//        redisTemplate.opsForValue().set(key, dishVOList);
        return Result.success(dishVOList);
    }
}
